import {
  Button, Col, Form, Input, message, Modal, Row, Select, Tooltip, TreeSelect,
} from 'antd'
import React, { PureComponent } from 'react'
import { saveIndex } from './api'
import { regExp } from '@/utils/regExp'

const { Item } = Form
const { Option } = Select

export default class NewIndexModal extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      visible: false,
      isEdit: false,
      isCheck: false,
      titleStr: '新建指标',
      id: '',
    }

    this.form = React.createRef()
  }

  // 新建指标打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onNewOpen = (pid) => {
    this.form.current && this.form.current.resetFields()
    this.setState({
      visible: true,
      isEdit: false,
      isCheck: false,
      titleStr: '新建指标',
    }, () => {
      pid !== '0' && pid && this.form.current && this.form.current.setFieldsValue({
        indexCatalogId: pid,
      })
    })
  }

  // 编辑指标打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onEditOpen = (record) => {
    const {
      ...restProps
    } = record
    this.setState({
      visible: true,
      isEdit: true,
      isCheck: false,
      titleStr: '编辑指标',
      id: record.id,
    }, () => {
      this.form.current && this.form.current.resetFields()
      this.form.current && this.form.current.setFieldsValue({
        ...restProps,
      })
    })
  }

  // 查看指标打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onCheckOpen = (record) => {
    const {
      analysisDimension,
      remark,
      ...restProps
    } = record
    this.setState({
      visible: true,
      isCheck: true,
      isEdit: false,
      titleStr: '查看指标',
      id: record.id,
    }, () => {
      this.form.current && this.form.current.resetFields()
      this.form.current && this.form.current.setFieldsValue({
        analysisDimension: analysisDimension || '--',
        remark: remark || '--',
        ...restProps,
      })
    })
  }

  closeModal = () => {
    this.setState({ visible: false })
  }

  onConfirm = () => {
    this.form.current.validateFields().then(values => {
      const {
        ...restProps
      } = values
      const postObj = { ...restProps }
      let megStr
      if (this.state.isEdit) {
        megStr = '编辑指标成功'
      } else {
        megStr = '新建指标成功'
      }
      if (this.state.isEdit) {
        postObj.id = this.state.id
      }
      saveIndex(postObj).then(
        (res) => {
          this.setState({
            visible: false,
            loading: false,
          }, () => {
            message.success(megStr)
            this.props.closeCallBack && this.props.closeCallBack()
          })
        },
        (error) => {
          this.setState({ loading: false })
        },
      )
    })
  }

  render() {
    const {
      visible, titleStr, loading, isCheck,
    } = this.state
    const { treeOptions, ownerArr } = this.props

    const treeOptionsTemp = treeOptions[0]?.pid === '-1' ? treeOptions[0]?.children : treeOptions

    const descRe = regExp.proName(1, 128)
    return (
      <Modal
        title={titleStr}
        visible={visible}
        width={720}
        onCancel={this.closeModal}
        maskClosable={isCheck}
        onOk={this.onConfirm}
        footer={
          isCheck ? null : (
            <>
              <Button
                onClick={this.closeModal}
              >
                取消
              </Button>
              <Button
                onClick={this.onConfirm}
                type="primary"
                loading={loading}
              >
                确定
              </Button>
            </>
          )
        }
      >
        <Form
          ref={this.form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
        >
          <Row>
            <Col span={24}>
              <Item
                label={
                  <span>
                    指标名称&nbsp;
                    <Tooltip
                      placement="bottomLeft"
                      title={(
                        <div>
                          <div>指标命名参考：</div>
                          <div>动作+度量</div>
                          <div>例如：生产抽烟机数、购买洗碗机用户数</div>
                          <div>时间周期+统计粒度+业务限定+原子指标</div>
                          <div>例如：2022年洗碗机杭州销售数量</div>
                        </div>
                      )}
                    >
                      <i className="iconfont icon-yiwentishi" />
                    </Tooltip>
                  </span>
                }
                name="name"
                rules={[
                  { required: true, message: '请输入指标名称' },
                  {
                    pattern: new RegExp(descRe.reg, 'g'),
                    message: descRe.text,
                  },
                ]}
              >
                <Input
                  placeholder="请输入指标名称"
                  disabled={isCheck}
                />
              </Item>
            </Col>
          </Row>
          {
            !isCheck && (
              <Row>
                <Col span={24}>
                  <Item
                    label="指标目录"
                    name="indexCatalogId"
                    rules={[{ required: true, message: '请选择指标目录' }]}
                  >
                    <TreeSelect
                      getPopupContainer={(triggerNode) => triggerNode.parentNode}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={treeOptionsTemp}
                      placeholder="请选择指标目录"
                      treeDefaultExpandAll
                      disabled={isCheck}
                      fieldNames={{
                        label: 'name', value: 'id', children: 'children',
                      }}
                      allowClear
                      showSearch
                      filterTreeNode={(input, treeNode) => treeNode.name.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    />
                  </Item>
                </Col>
              </Row>
            )
          }
          <Row>
            <Col span={24}>
              <Item
                label="业务定义"
                name="businessDef"
                validateTrigger="onBlur"
                rules={[
                  { required: true, message: '请输入业务定义' },
                  // {
                  //   pattern: new RegExp(regExp.name(1, 128).reg, 'g'),
                  //   message: regExp.name(1, 128).text,
                  // },
                ]}
              >
                <Input.TextArea
                  placeholder="请输入业务定义"
                  autoComplete="off"
                  rows="3"
                  disabled={isCheck}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Item
                label="计算规则"
                name="calculationRule"
                validateTrigger="onBlur"
                rules={[
                  { required: true, message: '请输入计算规则' },
                  // {
                  //   pattern: new RegExp(regExp.name(1, 128).reg, 'g'),
                  //   message: regExp.name(1, 128).text,
                  // },
                ]}
              >
                <Input.TextArea
                  placeholder="请输入计算规则"
                  autoComplete="off"
                  rows="3"
                  disabled={isCheck}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Item
                label="计算单位"
                name="unit"
              >
                <Input
                  disabled={isCheck}
                  placeholder="请输入计算单位"
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Item
                label={
                  <span>
                    时间粒度&nbsp;
                    <Tooltip
                      placement="topLeft"
                      title="计算指标的时间周期。"
                    >
                      <i className="iconfont icon-yiwentishi" />
                    </Tooltip>
                  </span>
                }
                name="timeGranularity"
                rules={[{ required: true, message: '请选择时间粒度' }]}
              >
                <Select
                  placeholder="请选择时间粒度"
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  disabled={isCheck}
                >
                  <Option value="day">日</Option>
                  <Option value="week">周</Option>
                  <Option value="month">月</Option>
                  <Option value="quarter">季</Option>
                  <Option value="year">年</Option>
                  <Option value="rt">实时</Option>
                </Select>
              </Item>
            </Col>
          </Row>
          {/* <Row>
            <Col span={24}>
              <Item
                label="数据Owner"
                name="dataOwnerId"
                rules={[{ required: true, message: '请选择数据Owner' }]}
              >
                <Select
                  placeholder="请选择数据Owner"
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  disabled={isCheck}
                >
                  {
                    ownerArr.map((item) => <Option value={item.id} key={item.id}>{item.ownerName}</Option>)
                  }
                </Select>
              </Item>
            </Col>
          </Row> */}
          <Row>
            <Col span={24}>
              <Item
                label="可用分析维度"
                name="analysisDimension"
              >
                <Input.TextArea
                  placeholder="请输入可用分析维度名称，多个名称请使用,隔开"
                  autoComplete="off"
                  rows="3"
                  disabled={isCheck}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Item
                label="备注"
                name="remark"
              >
                <Input.TextArea
                  placeholder="请输入备注内容"
                  autoComplete="off"
                  rows="3"
                  disabled={isCheck}
                />
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    )
  }
}
